import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;


// lukaszlewicki@op.pl smtp.poczta.onet.pl Test1234

public class SmtpMain {
  private static DataOutputStream dos;
  BufferedReader br;
  int delay = 2000;

  public static void main(String[] args) throws Exception {

    // String username = "bHVrYXN6bGV3aWNraUBvcC5wbA==";// lukaszlewicki@op.pl
    // String password = "VGVzdDEyMzQ="; // Test1234
    SmtpMain nn = new SmtpMain();
    nn.func();
  }

  public void func() throws Exception {
    String username = "bGxsbGV3aWNraUBnbWFpbC5jb20=\r\n";
    String password = "bWVMYW56MzAw\r\n";
    SSLSocket sock =
    // (SSLSocket) ((SSLSocketFactory) SSLSocketFactory.getDefault()).createSocket(
    // "smtp.poczta.onet.pl", 465);
        (SSLSocket) ((SSLSocketFactory) SSLSocketFactory.getDefault()).createSocket(
            "smtp.gmail.com", 465);
    // Socket sock = new Socket("smtp.gmail.com", 587);
    br = new BufferedReader(new InputStreamReader(sock.getInputStream()));
    (new Thread(new Runnable() {
      public void run() {
        try {
          String line;
          while ((line = br.readLine()) != null)
            System.out.println("SERVER: " + line);
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    })).start();
    dos = new DataOutputStream(sock.getOutputStream());
    send("EHLO smtp.gmail.com\r\n");

    // send("EHLO smtp.poczta.onet.pl\r\n");
    Thread.sleep(delay);
    send("AUTH LOGIN\r\n");
    Thread.sleep(delay);
    send(username);
    Thread.sleep(2 * delay);
    // String line;
    // while ((line = br.readLine()) == null)
    // Thread.sleep(100);
    send(password);
    Thread.sleep(2 * delay);
    // send("MAIL FROM: lukaszlewicki@op.pl\r\n");
    send("MAIL FROM: llllewicki@gmail.com\r\n");
    send("\r\n");
    Thread.sleep(delay);
    // send("RCPT TO: lukaszlewicki@op.pl\r\n");
    send("RCPT TO: llllewicki@gmail.com\r\n");
    Thread.sleep(delay);
    send("DATA\r\n");
    Thread.sleep(delay);
    send("Subject: Email test\r\n");
    Thread.sleep(delay);
    send("Test 1 2 3");
    Thread.sleep(delay);
    send("\r\n.\r\n");
    Thread.sleep(delay);
    send("QUIT\r\n");
  }

  private void send(String s) throws Exception {
    dos.writeBytes(s);
    System.out.println("CLIENT: " + s);
    // String line;
    // Thread.sleep(delay);
    // while ((line = br.readLine()) != null)
    // System.out.println("SERVER: " + line);
  }
}
